<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="设备名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入设备名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备类型" prop="type">
        <Aselect
          :options="typeList"
          v-model="queryParams.type"
        ></Aselect>
      </el-form-item>
      <el-form-item label="品牌" prop="brand">
        <el-input
          v-model="queryParams.brand"
          placeholder="请输入品牌"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="型号" prop="model">
        <el-input
          v-model="queryParams.model"
          placeholder="请输入型号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="位置" prop="location">
        <el-input
          v-model="queryParams.location"
          placeholder="请输入位置"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="购买日期" prop="purchaseDate">
        <el-date-picker
          clearable
          v-model="queryParams.purchaseDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择购买日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="设备状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择设备状态"
          clearable
        >
          <el-option
            v-for="dict in equipment_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="负责人" prop="responsiblePerson">
        <el-input
          v-model="queryParams.responsiblePerson"
          placeholder="请输入负责人"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="保修期" prop="warrantyPeriod">
        <el-input
          v-model="queryParams.warrantyPeriod"
          placeholder="请输入保修期"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="Search"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['equipment:equipment:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['equipment:equipment:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['equipment:equipment:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['equipment:equipment:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="equipmentList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
      />
      <el-table-column
        label="设备ID"
        align="center"
        prop="equipmentId"
      />
      <el-table-column
        label="设备名称"
        align="center"
        prop="name"
      />
      <el-table-column
        label="设备类型"
        align="center"
        prop="type"
      >
        <template #default="scope">
          <span>{{
            typeList.find(
              (res) => res.value == scope.row.type
            )?.label
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="位置"
        align="center"
        prop="location"
      />
      <el-table-column
        label="购买日期"
        align="center"
        prop="purchaseDate"
        width="180"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.purchaseDate, "{y}-{m}-{d}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="价格"
        align="center"
        prop="price"
      />
      <el-table-column
        label="设备状态"
        align="center"
        prop="status"
      >
        <template #default="scope">
          <dict-tag
            :options="equipment_status"
            :value="scope.row.status"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="负责人"
        align="center"
        prop="responsiblePerson"
      />
      <el-table-column
        label="保修期"
        align="center"
        prop="warrantyPeriod"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="300"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="EditPen"
            @click="repair(scope.row)"
            v-hasPermi="['equipment:equipment:edit']"
            style="color: deepskyblue"
            v-if="scope.row.status == 1"
            >报修</el-button
          >
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['equipment:equipment:edit']"
            v-if="
              scope.row.status == 1 || scope.row.status == 2
            "
            >修改</el-button
          >
          <el-button
            link
            type="danger"
            icon="WarnTriangleFilled"
            @click="scrap(scope.row)"
            v-hasPermi="['equipment:equipment:edit']"
            v-if="scope.row.status == 1"
            >报废设备</el-button
          >
          <el-button
            link
            type="warning"
            icon="RefreshRight"
            @click="startUsing(scope.row)"
            v-hasPermi="['equipment:equipment:edit']"
            v-if="scope.row.status == 3"
            >启用设备</el-button
          >
          <el-button
            link
            type="danger"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['equipment:equipment:remove']"
            v-if="scope.row.status == 3"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改后勤设备对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="500px"
      align-center
      center
    >
      <el-form
        ref="equipmentRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="设备名称" prop="name">
          <el-input
            v-model="form.name"
            placeholder="请输入设备名称"
          />
        </el-form-item>
        <el-form-item label="设备类型" prop="type">
          <Aselect
            :options="typeList"
            v-model="form.type"
          ></Aselect>
        </el-form-item>
        <el-form-item label="品牌" prop="brand">
          <el-input
            v-model="form.brand"
            placeholder="请输入品牌"
          />
        </el-form-item>
        <el-form-item label="型号" prop="model">
          <el-input
            v-model="form.model"
            placeholder="请输入型号"
          />
        </el-form-item>
        <el-form-item label="位置" prop="location">
          <el-input
            v-model="form.location"
            placeholder="请输入位置"
          />
        </el-form-item>
        <el-form-item label="购买日期" prop="purchaseDate">
          <el-date-picker
            clearable
            v-model="form.purchaseDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择购买日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input
            v-model="form.price"
            placeholder="请输入价格"
          />
        </el-form-item>
        <el-form-item
          label="负责人"
          prop="responsiblePerson"
        >
          <el-input
            v-model="form.responsiblePerson"
            placeholder="请输入负责人"
          />
        </el-form-item>
        <el-form-item label="保修期" prop="warrantyPeriod">
          <el-input
            v-model="form.warrantyPeriod"
            placeholder="请输入保修期"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input
            v-model="form.remarks"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm"
            >确 定</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 报修对话框 -->
    <el-dialog
      :title="repairTitle"
      v-model="repairOpen"
      width="500px"
      append-to-body
    >
      <el-form
        ref="repairRef"
        :model="formRepair"
        :rules="rulesRepair"
        label-width="100px"
      >
        <el-form-item label="后勤设备" prop="equipmentId">
          {{ repairDevice }}
        </el-form-item>
        <el-form-item label="故障类型" prop="faultType">
          <el-select
            v-model="formRepair.faultType"
            placeholder="请选择故障类型"
          >
            <el-option
              v-for="dict in equipment_fault_type_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="报修人" prop="reporter">
          <el-input
            v-model="formRepair.reporter"
            placeholder="请输入报修人"
          />
        </el-form-item>
        <el-form-item
          label="维修负责人"
          prop="repairPerson"
        >
          <el-input
            v-model="formRepair.repairPerson"
            placeholder="请输入维修负责人"
          />
        </el-form-item>
        <el-form-item
          label="故障描述"
          prop="faultDescription"
        >
          <el-input
            v-model="formRepair.faultDescription"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="设备图片" prop="equipmentImg">
          <image-upload v-model="formRepair.equipmentImg" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="repairEquipment"
            >确 定</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Equipment">
import {
  listEquipment,
  getEquipment,
  delEquipment,
  addEquipment,
  updateEquipment
} from "@/api/equipment/equipment";
import {
  listRepair,
  getRepair,
  delRepair,
  addRepair,
  updateRepair
} from "@/api/repair/repair";
import { listType } from "@/api/type/type";
import Aselect from "@/components/Select/Aselect.vue";
import { onMounted } from "vue";

const { proxy } = getCurrentInstance();
const { equipment_status, equipment_fault_type_status } =
  proxy.useDict(
    "equipment_status",
    "equipment_fault_type_status",
    "equipment_repair_status"
  );

const equipmentList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    type: null,
    brand: null,
    model: null,
    location: null,
    purchaseDate: null,
    price: null,
    status: null,
    maintenanceCycle: null,
    lastMaintenanceDate: null,
    nextMaintenanceDate: null,
    responsiblePerson: null,
    warrantyPeriod: null,
    remarks: null
  },
  rules: {
    name: [
      {
        required: true,
        message: "设备名称不能为空",
        trigger: "blur"
      }
    ],
    status: [
      {
        message: "设备状态不能为空",
        trigger: "change"
      }
    ]
  },
  formRepair: {},
  rulesRepair: {
    repairId: [
      {
        required: true,
        message: "维修单号不能为空",
        trigger: "blur"
      }
    ],
    equipmentId: [
      {
        required: true,
        message: "设备ID不能为空",
        trigger: "blur"
      }
    ]
  }
});

const {
  queryParams,
  form,
  rules,
  formRepair,
  rulesRepair
} = toRefs(data);

const repairOpen = ref(false);
const repairTitle = ref("报修设备");
const repairDevice = ref("");
// 表单重置
function resetRepair() {
  form.value = {
    repairId: null,
    equipmentId: null,
    faultType: null,
    faultDescription: null,
    reporter: null,
    reportTime: null,
    repairStatus: null,
    repairPerson: null,
    startTime: null,
    completeTime: null,
    repairCost: null,
    solution: null,
    partsReplaced: null,
    repairNotes: null,
    equipmentImg: null
  };
  proxy.resetForm("repairRef");
}
function repair(row) {
  repairOpen.value = true;
  repairDevice.value = row.name;
  formRepair.value.equipmentId = row.equipmentId;
  resetRepair();
}

const typeList = ref([]);
// 获取设备类型
function getTypeList() {
  listType({ pageNum: 1, pageSize: 100 }).then(
    (response) => {
      typeList.value = response.rows.map((res) => {
        return {
          value: res.typeId,
          label: res.typeName
        };
      });
    }
  );
}

onMounted(() => {
  getList();
  getTypeList();
});

/** 查询后勤设备列表 */
function getList() {
  loading.value = true;
  listEquipment(queryParams.value).then((response) => {
    equipmentList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  repairOpen.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    equipmentId: null,
    type: null,
    name: null,
    type: null,
    brand: null,
    model: null,
    location: null,
    purchaseDate: null,
    price: null,
    status: null,
    maintenanceCycle: null,
    warrantyPeriod: null,
    remarks: null,
    createTime: null,
    updateTime: null
  };
  proxy.resetForm("equipmentRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.equipmentId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加后勤设备";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _equipmentId = row.equipmentId || ids.value;
  getEquipment(_equipmentId).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改后勤设备";
  });
}

// 提交报修
function repairEquipment() {
  proxy.$refs["repairRef"].validate((valid) => {
    if (valid) {
      if (formRepair.value.repairId != null) {
        updateRepair(formRepair.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          repairOpen.value = false;
          getList();
        });
      } else {
        addRepair(formRepair.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          repairOpen.value = false;
          getList();
        });
      }
    }
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["equipmentRef"].validate((valid) => {
    if (valid) {
      if (form.value.equipmentId != null) {
        updateEquipment(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addEquipment(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _equipmentIds = row.equipmentId || ids.value;
  proxy.$modal
    .confirm(
      '是否确认删除后勤设备编号为"' +
        _equipmentIds +
        '"的数据项？'
    )
    .then(function () {
      return delEquipment(_equipmentIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 报废设备 */
function scrap(row) {
  const _equipmentIds = row.equipmentId || ids.value;
  proxy.$modal
    .confirm("是否确认报废设备" + row.name)
    .then(function () {
      updateEquipment({
        equipmentId: _equipmentIds,
        status: "3"
      }).then((response) => {
        proxy.$modal.msgSuccess("设备报废成功");
        getList();
      });
    })
    .then(() => {
      getList();
    })
    .catch(() => {});
}

/** 设备重新启用 */
function startUsing(row) {
  const _equipmentIds = row.equipmentId || ids.value;
  proxy.$modal
    .confirm("是否确认重新启用设备" + row.name)
    .then(function () {
      updateEquipment({
        equipmentId: _equipmentIds,
        status: "1"
      }).then((response) => {
        proxy.$modal.msgSuccess("设备报废成功");
        getList();
      });
    })
    .then(() => {
      getList();
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "equipment/equipment/export",
    {
      ...queryParams.value
    },
    `equipment_${new Date().getTime()}.xlsx`
  );
}

onMounted(() => {
  getList();
});
</script>
